import pymongo
import pymysql.cursors


def setModelNo():
    myclient = pymongo.MongoClient('mongodb://root:Tsp%40_baic123@dds-2ze0505b18b8f0241.mongodb.rds.aliyuncs.com:3717')
    mydb = myclient["auto_tsp_baic_log_test"]  # mysql的database
    mycol = mydb["PlatformLoggerMain"]  # mysql的table

    vehicleList = getVinAndModelNo()
    mongoVinList = mycol.distinct("vin")
    index = 0
    for vinMongo in mongoVinList:
        for vehicle in  vehicleList:
            vin = vehicle.get("vin")
            tmModelNo = vehicle.get("tm_model_no")
            if vin == vinMongo:
                index = index+1
                print("更新条数:",index)
                print("当前更新的vin和tmModelNo是:",vin,tmModelNo)
                mycol.update_many({"vin": vin}, {"$set": {"tmModelNo": tmModelNo}})

def getVinAndModelNo():
    print("获取vin和modelNo的集合")
    connect = pymysql.Connect(
        host='rm-2ze6imgdslrz1j3l1.mysql.rds.aliyuncs.com',
        port=3306,
        user='tsp_user',
        passwd='Iflytek@baic2020',
        db='rtm_cloud',
        charset='utf8'
    )
    # cursor = connect.cursor()
    # 这样使用的是dict
    cursor = connect.cursor(pymysql.cursors.DictCursor)
    sql = 'select distinct vin,tm_model_no from t_vehicle_info '
    count = cursor.execute(sql)
    res = cursor.fetchall()
    cursor.close()
    connect.close()
    print("vin关系条数:",count)
    # for row in res:
    #     # print(row)
    #     print(row.get("vin"))
    return res

def testMd():
    mongoVinList=["vintestwc11111112","vintestwc11111111","vintestwc11111113","vintestwc11111114"]
    vinList = [["vintestwc11111112","modelNo1"],["vin2","modelNo1"],["vin3","modelNo1"]]
    for vin in mongoVinList:
        print("当前vin是",vin)
        for vehicle in vinList:
            if vin == vehicle[0]:
                print("vin匹配成功",vin)
if __name__ == '__main__':
    setModelNo()
    # testMd
